#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""证券账户ATM风格登录功能
实现像银行柜员机一样，用户输入证券账户或卡号后直接进入交易所主页面的功能
"""

import os
import sys
import json
import time
from datetime import datetime

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                            QLabel, QLineEdit, QPushButton, QMessageBox, QTabWidget, 
                            QTableWidget, QTableWidgetItem, QFormLayout, QComboBox, QGroupBox)
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QFont, QBrush, QColor

from utils.logger import Logger
from api_integration import APIIntegration
from utils.account_manager import account_manager

class ATMLoginDialog(QWidget):
    """ATM风格登录对话框"""
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent = parent
        self.init_ui()
        
    def init_ui(self):
        """初始化UI界面"""
        # 设置窗口属性
        self.setWindowTitle("证券账户登录")
        self.setMinimumWidth(400)
        self.setMinimumHeight(300)
        
        # 主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(30, 30, 30, 30)
        main_layout.setSpacing(20)
        
        # Logo和标题
        title_label = QLabel("量子金融分析系统")
        font = QFont()
        font.setBold(True)
        font.setPointSize(20)
        title_label.setFont(font)
        title_label.setAlignment(Qt.AlignCenter)
        main_layout.addWidget(title_label)
        
        subtitle_label = QLabel("请输入您的证券账户信息")
        subtitle_label.setAlignment(Qt.AlignCenter)
        main_layout.addWidget(subtitle_label)
        
        # 账户输入表单
        form_group = QGroupBox()
        form_layout = QFormLayout(form_group)
        
        # 平台选择
        self.platform_selector = QComboBox()
        self.platform_selector.setEditable(True)
        self.platform_selector.setPlaceholderText("请选择或输入交易平台")
        # 添加常见交易平台选项
        self.platform_selector.addItem("tencent", "tencent")
        self.platform_selector.addItem("招商证券", "zhaoshang")
        self.platform_selector.addItem("中信证券", "zhongxin")
        self.platform_selector.addItem("国泰君安", "guotaijun'an")
        
        # 账户输入框
        self.account_input = QLineEdit()
        self.account_input.setPlaceholderText("请输入证券账户号或卡号")
        # 设置回显模式，只显示最后4位数字
        self.account_input.setEchoMode(QLineEdit.PasswordEchoOnEdit)
        
        # 添加到表单
        form_layout.addRow("交易平台:", self.platform_selector)
        form_layout.addRow("证券账户号:", self.account_input)
        
        main_layout.addWidget(form_group)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        # 登录按钮
        self.login_button = QPushButton("登录")
        self.login_button.setFixedHeight(40)
        self.login_button.clicked.connect(self.handle_login)
        self.login_button.setDefault(True)
        
        # 取消按钮
        cancel_button = QPushButton("取消")
        cancel_button.setFixedHeight(40)
        cancel_button.clicked.connect(self.close)
        
        button_layout.addWidget(self.login_button)
        button_layout.addWidget(cancel_button)
        
        main_layout.addLayout(button_layout)
        
        # 设置样式
        self.setStyleSheet("""
            QPushButton {
                font-size: 14px;
                font-weight: bold;
            }
            QPushButton#login_button {
                background-color: #4CAF50;
                color: white;
            }
            QLineEdit, QComboBox {
                padding: 8px;
                font-size: 14px;
            }
        """)
        
    def handle_login(self):
        """处理登录请求"""
        # 获取用户输入
        platform = self.platform_selector.currentText().strip()
        account_number = self.account_input.text().strip()
        
        # 验证输入
        if not platform:
            QMessageBox.warning(self, "警告", "请选择或输入交易平台")
            return
        
        if not account_number:
            QMessageBox.warning(self, "警告", "请输入证券账户号或卡号")
            return
        
        # 显示加载状态
        self.login_button.setText("登录中...")
        self.login_button.setEnabled(False)
        QApplication.processEvents()
        
        try:
            # 查找或创建账户
            account_id, is_new = self._find_or_create_account(platform, account_number)
            
            if account_id:
                Logger.log_info(f"用户登录成功: 平台={platform}, 账户={account_number}")
                
                # 切换到主窗口并显示交易所页面
                if self.parent:
                    self.parent.switch_to_exchange_page(account_id)
                
                self.close()
                return True
            else:
                QMessageBox.warning(self, "登录失败", "无法找到或创建账户，请检查输入信息")
                return False
        except Exception as e:
            Logger.log_error(f"登录过程中发生错误: {str(e)}")
            QMessageBox.critical(self, "登录错误", f"登录过程中发生错误: {str(e)}")
            return False
        finally:
            # 恢复按钮状态
            self.login_button.setText("登录")
            self.login_button.setEnabled(True)
    
    def _find_or_create_account(self, platform, account_number):
        """查找或创建账户
        
        Args:
            platform (str): 交易平台
            account_number (str): 证券账户号或卡号
        
        Returns:
            tuple: (account_id, is_new)
        """
        # 查找是否已存在该账户
        accounts = account_manager.get_all_accounts()
        
        # 检查是否存在匹配的账户（通过account_name或description）
        for account in accounts:
            if (account.get('account_name') == account_number or 
                account.get('description') == account_number) and 
                account.get('platform') == platform:
                return account['account_id'], False
        
        # 如果不存在，则创建新账户
        # 生成唯一的账户ID（使用平台类型+账户号后8位）
        account_id_part = account_number[-8:] if len(account_number) >= 8 else account_number
        account_id = f"{platform}_{account_id_part}"
        
        # 添加账户
        result = account_manager.add_account(
            platform=platform,
            account_name=account_number,
            api_key=f"{platform}_{account_id_part}_key",
            api_secret=f"{platform}_{account_id_part}_secret",
            description=account_number
        )
        
        return result, True

class EnhancedMainWindow(QMainWindow):
    """增强版主窗口，支持ATM风格登录"""
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        # 初始化核心组件
        self.api_integration = APIIntegration()
        
        # 先显示登录对话框
        self.show_atm_login_dialog()
    
    def show_atm_login_dialog(self):
        """显示ATM风格登录对话框"""
        self.login_dialog = ATMLoginDialog(self)
        self.login_dialog.show()
    
    def switch_to_exchange_page(self, account_id):
        """切换到交易所主页面
        
        Args:
            account_id (str): 账户ID
        """
        # 切换到指定账户
        if self.api_integration.switch_account(account_id):
            Logger.log_info(f"已切换到账户: {account_id}")
            
            # 这里应该是初始化主窗口UI并跳转到交易所页面的代码
            # 由于我们是在原有的MainWindow基础上增强，这里简化处理
            self.setWindowTitle("量子金融分析系统 - 交易所页面")
            
            # 创建交易所页面
            self.create_exchange_main_page()
            
            # 显示主窗口
            self.show()
        else:
            QMessageBox.warning(self, "切换失败", f"无法切换到账户: {account_id}")
    
    def create_exchange_main_page(self):
        """创建交易所主页面"""
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(10)
        
        # 创建选项卡
        self.tab_widget = QTabWidget()
        
        # 添加交易所主页面选项卡（行情作为默认显示的主页面）
        self.market_tab = self.create_market_tab()
        self.trade_tab = self.create_trade_tab()
        self.portfolio_tab = self.create_portfolio_tab()
        
        self.tab_widget.addTab(self.market_tab, "行情")
        self.tab_widget.addTab(self.trade_tab, "交易")
        self.tab_widget.addTab(self.portfolio_tab, "持仓")
        
        # 添加到主布局
        main_layout.addWidget(self.tab_widget)
        
        # 状态栏信息
        self.statusBar().showMessage("就绪")
        
        # 初始化数据
        self.init_market_data()
        
        # 设置定时器，用于刷新行情数据
        self.market_data_timer = QTimer(self)
        self.market_data_timer.timeout.connect(self.update_market_data)
        self.market_data_timer.start(30000)  # 每30秒刷新一次
    
    def create_market_tab(self):
        """创建行情选项卡（交易所主页面）"""
        tab = QWidget()
        layout = QVBoxLayout(tab)
        
        # 搜索框和按钮
        search_layout = QHBoxLayout()
        
        # 添加产品类型选择器
        self.product_type_selector = QComboBox()
        self.product_type_selector.addItem("股票", "stock")
        self.product_type_selector.addItem("基金", "fund")
        self.product_type_selector.addItem("债券", "bond")
        self.product_type_selector.addItem("期货", "future")
        
        self.stock_code_input = QLineEdit()
        self.stock_code_input.setPlaceholderText("输入代码，如：SH600000")
        
        search_button = QPushButton("查询")
        
        search_layout.addWidget(QLabel("产品类型："))
        search_layout.addWidget(self.product_type_selector)
        search_layout.addWidget(self.stock_code_input)
        search_layout.addWidget(search_button)
        
        # 行情表格
        self.market_table = QTableWidget()
        self.market_table.setColumnCount(11)
        self.market_table.setHorizontalHeaderLabels([
            "代码", "名称", "当前价", "涨跌幅", "开盘价", "最高价", 
            "最低价", "成交量(万)", "成交额(万)", "换手率", "更新时间"
        ])
        
        # 设置表格自适应
        header = self.market_table.horizontalHeader()
        for i in range(self.market_table.columnCount()):
            header.setSectionResizeMode(i, QHeaderView.Stretch)
        
        # 添加到布局
        layout.addLayout(search_layout)
        layout.addWidget(self.market_table)
        
        return tab
    
    def create_trade_tab(self):
        """创建交易选项卡"""
        tab = QWidget()
        layout = QHBoxLayout(tab)
        
        # 左侧交易表单
        form_group = QGroupBox("交易委托")
        form_layout = QFormLayout()
        
        self.trade_stock_code = QLineEdit()
        self.trade_order_type = QComboBox()
        self.trade_order_type.addItems(["买入", "卖出"])
        self.trade_quantity = QComboBox()
        # 添加常见交易数量选项
        for qty in [100, 500, 1000, 5000, 10000]:
            self.trade_quantity.addItem(str(qty))
        
        # 添加到表单
        form_layout.addRow("股票代码:", self.trade_stock_code)
        form_layout.addRow("交易类型:", self.trade_order_type)
        form_layout.addRow("交易数量:", self.trade_quantity)
        
        layout.addWidget(form_group)
        
        return tab
    
    def create_portfolio_tab(self):
        """创建持仓选项卡"""
        tab = QWidget()
        layout = QVBoxLayout(tab)
        
        # 持仓表格
        self.portfolio_table = QTableWidget()
        self.portfolio_table.setColumnCount(9)
        self.portfolio_table.setHorizontalHeaderLabels([
            "股票代码", "股票名称", "持仓数量", "持仓成本", "当前价", 
            "市值", "浮动盈亏", "盈亏比例", "更新时间"
        ])
        
        # 设置表格自适应
        header = self.portfolio_table.horizontalHeader()
        for i in range(self.portfolio_table.columnCount()):
            header.setSectionResizeMode(i, QHeaderView.Stretch)
        
        # 添加到布局
        layout.addWidget(self.portfolio_table)
        
        return tab
    
    def init_market_data(self):
        """初始化市场数据"""
        # 预加载一些股票数据作为示例
        sample_stocks = ["SH600000", "SZ000001", "SH600519", "SZ000858", "SZ002594"]
        
        # 初始化行情表格
        self.market_table.setRowCount(len(sample_stocks))
        
        # 尝试通过API获取数据或使用模拟数据
        try:
            # 调用API获取数据
            result = self.api_integration.get_market_data(sample_stocks)
            
            # 填充表格数据
            for i, stock_code in enumerate(sample_stocks):
                # 创建表格项（简化版本）
                code_item = QTableWidgetItem(stock_code)
                name_item = QTableWidgetItem(f"股票{i+1}")
                price_item = QTableWidgetItem("--")
                
                # 设置居中对齐
                for item in [code_item, name_item, price_item]:
                    item.setTextAlignment(Qt.AlignCenter)
                
                # 添加到表格
                self.market_table.setItem(i, 0, code_item)
                self.market_table.setItem(i, 1, name_item)
                self.market_table.setItem(i, 2, price_item)
        except Exception as e:
            Logger.log_error(f"初始化市场数据失败: {str(e)}")
    
    def update_market_data(self):
        """更新市场数据"""
        try:
            # 这里应该是更新市场数据的代码
            # 简化实现
            self.statusBar().showMessage(f"行情数据已更新于 {datetime.now().strftime('%H:%M:%S')}")
        except Exception as e:
            Logger.log_error(f"更新市场数据失败: {str(e)}")

def main():
    """应用程序主入口"""
    # 创建应用程序实例
    app = QApplication(sys.argv)
    
    # 创建增强版主窗口
    window = EnhancedMainWindow()
    
    # 运行应用程序
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()